<template>
  <view class="left-right">
    <scroll-view scroll-y class="left">
      <view class="title">知识点</view>
      <view
        v-for="item in knowledgeList"
        :key="item.id"
        @tap="onClickKnowledge(item.id)"
        class="item"
        :class="{ active: item.id === state.knowledge_id }"
      >
        <text class="name">{{ item.name }}</text>
      </view>
    </scroll-view>
    <scroll-view class="right" scroll-y>
      <!-- <view class="subject">
        <text>学科：</text>
        <radio-group @change="subject_change">
          <label v-for="(item, index) in subject_list" :key="index">
            <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
            {{ item.name }}
          </label>
        </radio-group>
      </view> -->
      <view class="type_select">
        <text>类型：</text>
        <radio-group @change="type_change">
          <label v-for="(item, index) in type_list" :key="index">
            <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
            {{ item.name }}
          </label>
        </radio-group>
      </view>
      <view class="content">
        <!-- :extra="item.download_total" -->
        <uni-card
          v-for="item in guidePaperList"
          :key="item.id"
          :title="item.title"
          class="guide-content"
          :sub-title="item.add_date"
          @click="onClickCard(item.file)"
        >
          <text v-if="item.type == 1" class="guide-content">文件类型：docx</text>
          <text v-if="item.type == 2" class="guide-content">文件类型：pptx</text>
          <rich-text :nodes="item.remark" class="uni-h6 guide-content"></rich-text>
          <text class="guide-content">库币：{{ item.bank_point }}</text>
          <button
            @tap="onClickDownloadGuide(item.id, item.type, item.bank_point, item.file)"
            size="mini"
            class="button_content"
            type="primary"
          >
            下载
          </button>
        </uni-card>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { SubjectItem, GuideTypeItem, GuidePaperItem, KnowledgeItem } from '@/types/home'
import { getGuidePaperAPI, getKnowledgeAPI, postGuidePaperFeiAPI } from '@/services/home'
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { useMemberStore } from '@/stores'
import { baseURL, baseURL_noapi, downloadSyncFile } from '@/utils/http'
// 获取会员Store
let memberStore = reactive<any>({})
const state = reactive({
  subject_id: 1,
  knowledge_id: 0,
  type: 0,
  paper_type: 0,
  page: 1,
  size: 10,
  total: 0,
})

const subject_list = ref<SubjectItem[]>([
  { name: '数学', value: '1', checked: true },
  { name: '语文', value: '2', checked: false },
  { name: '科学', value: '3', checked: false },
])
const type_list = ref<GuideTypeItem[]>([
  { name: '全部', value: '0', checked: true },
  { name: '新课', value: '1', checked: false },
  { name: '复习', value: '2', checked: false },
])
// 下载数转字符串
const downloadTotal2String = (value: number) => {
  return String(value)
}
// 下载导学案
const onClickDownloadGuide = async (id: number, type: number, bank_point: number, file: string) => {
  // 如果余额不足，则提示无法下载
  let user_bank_point = memberStore.profile.bank_point
  if (bank_point > user_bank_point) {
    uni.showToast({ icon: 'error', title: '你的库币余额不足，无法下载' })
    return 0
  }
  console.log('下载导学id', id)
  let file_name = 'download.docx'
  if (type === 2) {
    file_name = 'download.pptx'
  }
  let params_data = {
    paper_id: id,
  }
  uni.showLoading({ title: '下载中...' })
  let current_date = new Date()
  let date =
    current_date.getFullYear() +
    '-' +
    (current_date.getMonth() + 1).toString() +
    '-' +
    current_date.getDate()
  let new_file_name = date + '导学案' + '.docx'
  const result = await downloadSyncFile(baseURL_noapi + '/' + file, new_file_name, params_data)
  if (result == true) {
    console.log('文件打开成功，扣除库币')
    const res_fei = await postGuidePaperFeiAPI(params_data)
    if (res_fei.code == 200) {
      console.log('扣款成功')
    } else {
      console.log('扣款失败！')
    }
  } else {
    console.log('下载失败，不扣除库币')
  }
  // download_request(params_data, baseURL_noapi + '/' + file, new_file_name)
  // downloadFile(url, file_name, params)
}
// 知识点点击事件，重新获取该知识点的导学案
const onClickKnowledge = (id: number) => {
  console.log('知识点改变：', id)
  state.knowledge_id = id
  reGetGuideData()
}
// 点击卡片事件
const onClickCard = (file: string) => {
  console.log('预览导学案', file)
}
// 学科改变了,重新获取该学科的知识点
const subject_change = (e: any) => {
  console.log('学科改变：', e.target.value)
  state.subject_id = e.target.value
  reGetKnowledgeData()
}
// 课型改变了，重新获取该课型的导学案
const type_change = (e: any) => {
  console.log('类型改变：', e.target.value)
  state.paper_type = e.target.value
  reGetGuideData()
}
let guideParams = {
  id: state.knowledge_id,
  paper_type: state.paper_type,
  page: state.page,
  size: state.size,
}
const guidePaperList = ref<GuidePaperItem[]>([])
// 获取导学案
const getGuidePaperData = async () => {
  let guideParams = {
    id: state.knowledge_id,
    paper_type: state.paper_type,
    page: state.page,
    size: state.size,
  }
  const res = await getGuidePaperAPI(guideParams)
  console.log('所有导学案：', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    guidePaperList.value = res.results
    state.total = res.total
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 获取知识点api的参数
let subjectParams = {
  subject_id: state.subject_id,
}
const knowledgeList = ref<KnowledgeItem[]>([])
const getKnowledgeData = async () => {
  const res = await getKnowledgeAPI(subjectParams)
  console.log('知识点：', res.results)
  if (Array.isArray(res.results) && res.results.length > 0) {
    knowledgeList.value = res.results
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 重新获取知识点，重新修改参数，再发送api
const reGetKnowledgeData = () => {
  subjectParams = { subject_id: state.subject_id }
  console.log('获取知识点的参数', subjectParams)
  getKnowledgeData()
}
// 重新获取导学案，重新修改参数，再发送api
const reGetGuideData = () => {
  guideParams = {
    id: state.knowledge_id,
    paper_type: state.paper_type,
    page: state.page,
    size: state.size,
  }
  console.log('导学案参数', guideParams)
  getGuidePaperData()
}
// 用于上拉触底新增试题数据
const addPaperData = async () => {
  guideParams = {
    id: state.knowledge_id,
    paper_type: state.paper_type,
    page: state.page + 1,
    size: state.size,
  }
  const res = await getGuidePaperAPI(guideParams)
  // console.log('根据知识点获取题目：', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    guidePaperList.value.push(...res.results)
    state.page += 1
    state.total = res.total
  } else {
    uni.showToast({ icon: 'error', title: '触底添加数据失败' })
  }
}
// 页面加载
onLoad(async () => {
  // console.log('页面加载')
  getGuidePaperData()
  getKnowledgeData()
})
// 下拉刷新
onPullDownRefresh(() => {
  console.log('下拉刷新')
  guideParams = {
    id: state.knowledge_id,
    paper_type: state.paper_type,
    page: 1,
    size: state.size,
  }
  getGuidePaperData()
  uni.stopPullDownRefresh()
})
// 自定义触底加载更多数据
onReachBottom(async () => {
  console.log('触底拉')
  console.log('当前列表长度：', guidePaperList.value.length)
  console.log('总共长度：', state.total)
  if (guidePaperList.value.length >= state.total) {
    uni.showToast({ title: '没有更多数据了！', icon: 'none' })
  } else {
    addPaperData()
  }
})
</script>

<style lang="scss" scoped>
.left-right {
  display: flex;
  // flex-flow: row nowrap;
  flex: 1;
  min-height: 400rpx;
}

.left {
  display: flex;
  // flex-flow: column nowrap;
  // justify-content: left;
  // align-items: flex-start;
  flex: none;
  width: 180rpx;
  overflow: hidden;
  background-color: #f6f6f6;

  .item {
    display: flex;
    // flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
    height: 80rpx;
    font-size: 25rpx;
    color: #596c63;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      left: 42rpx;
      bottom: 0;
      width: 96rpx;
      border-top: 1rpx solid #e3e4e7;
    }
  }

  .active {
    background-color: fff;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: 8rpx;
      height: 100%;
      background-color: #0bba88d7;
    }
  }

  .title {
    font-size: 28rpx;
    font-weight: bold;
    overflow: hidden;
  }
}

.left .item:last-child::after,
.left .active::after {
  display: none;
}

.name {
  padding: 3rpx;
  font-size: 22rpx;
  color: #333;
}

.right {
  overflow-y: scroll;
  font-size: 28rpx;
  padding: 1rpx;

  .button_content {
    font-size: 25rpx;
    text-align: left;
  }
}

.subject {
  font-size: 30rpx;
  display: flex;
  flex-flow: row nowrap;
}

.type_select {
  font-size: 30rpx;
  display: flex;
  flex-flow: row nowrap;
}

.content {
  font-size: 27rpx;
  display: flex;
  flex-flow: row wrap;
  height: 100vh;
}

.guide-content {
  font-size: 27rpx;
  display: flex;
  flex-flow: column nowrap;
}
</style>
